package com.demo.zhihu.web;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.demo.zhihu.model.User;
import com.demo.zhihu.service.UserService;

import cn.techarts.dragonfly.app.helper.Cryptor;
import cn.techarts.dragonfly.web.WebContext;
import cn.techarts.dragonfly.web.rest.Get;
import cn.techarts.dragonfly.web.rest.Post;
import cn.techarts.dragonfly.web.rest.Restful;

@Singleton
@Restful
public class UserWebService {

    @Inject
    private UserService service;

    @Post("/user/{name}/{mobile}/{password}")
    public User register(WebContext arg) {
        var name = arg.at(0);
        var mobile = arg.at(1);
        var passwd = arg.at(2);
        if(mobile == null) {
            arg.error(-1, "Mobile is required");
            return null;
        }
        if(passwd == null || passwd.length() < 6) {
            arg.error(-2, "The password is 6 letters at least");
            return null;
        }
        var result = service.register(name, mobile, passwd);
        if(result == null) {
            arg.error(-6, "The mobile is duplicated");
        }
        return result;
    }

    @Get("/user/{mobile}/{password}")
    public User login(WebContext arg) {
        var mobile = arg.at(0);
        var passwd = arg.at(1);
        if(mobile == null) {
            arg.error(-1, "Mobile is required");
            return null;
        }
        if(passwd == null || passwd.length() < 6) {
            arg.error(-2, "The password is 6 letters at least");
            return null;
        }
        var result = service.login(mobile, passwd);
        if(result == null) {
            arg.error(-3, "The mobile or password is in correct");
        }
        return result;
    }
    
    @Get("/user/{id}/profile/{page}")
    public User getProfile(WebContext arg) {
        var id = arg.intAt(0);
        var page = arg.intAt(1);
        var result = service.getMyProfile(id, page);
        if(result == null) {
            arg.error(-333, "Can not find the user");
        }
        return result;
    }
}